#include "gameroom.h"
#include<QPainter>
#include<QPixmap>
#include<QIcon>
#include<QTimer>
#include<QPushButton>
#include<QMessageBox>
#include<QFile>
#include<QTextStream>
#include"gameselect.h"


gameroom::gameroom(QWidget *parent) : QWidget(parent)
{
    this->setFixedSize(1500,1000);
    this->setWindowIcon(QIcon(":res/ico.png"));
    this->setWindowTitle("游戏房间");


    //初始化贪吃蛇
    snakeList.push_back(QRectF(this->width()*0.5,this->height()*0.5,KSnakeNodeWidth,KSnakeNodeHeight));

    moveUp();
    moveUp();
    moveUp();


    //创建食物
    createNewFood();

    timer = new QTimer(this);

    connect(timer,&QTimer::timeout,[=]{
        int cnt =1 ;

        if(snakeList.front().intersects(foodRect))
        {
            //intersects判断会不会相交
            createNewFood();
            cnt++;
            QSound::play(":res/eatfood.wav");
        }

        while (cnt--) {
            switch (moveDirect) {
                case SnakeDirect::UP:
                    moveUp();
                    break;
                case SnakeDirect::DOWN:
                    moveDown();
                    break;
                case SnakeDirect::LEFT:
                    moveLeft();
                    break;
                case SnakeDirect::RIGHT:
                    moveRight();
                    break;
            }
        }

        snakeList.pop_back();//删除最后一个节点
        update();
    });

    //开始暂停
    QPushButton * strBtn = new QPushButton(this);
    QPushButton * stopBtn = new QPushButton(this);

    strBtn->move(1270,100);
    stopBtn->move(1270,170);
    strBtn->setText("开始");
    strBtn->setShortcut(QKeySequence(Qt::Key_C+Qt::CTRL));
    stopBtn->setText("暂停");
    stopBtn->setShortcut(QKeySequence(Qt::Key_V+Qt::CTRL));

    QFont font("楷体",20);
    strBtn->setFont(font);
    stopBtn->setFont(font);


    connect(strBtn,&QPushButton::clicked,[=]{

        sound = new QSound(":res/Trepak.wav");
        sound->play();
        sound->setLoops(-1);//一直循环播放

        isGameStart = true;
        timer->start(moveTime);
    });

    connect(stopBtn,&QPushButton::clicked,[=]{
        isGameStart = false;
        timer->stop();
        sound->stop();

    });

    //方向控制
    QPushButton*up= new QPushButton(this);
    QPushButton*down= new QPushButton(this);
    QPushButton*left= new QPushButton(this);
    QPushButton*right= new QPushButton(this);

    up->move(1320,750);
    down->move(1320,900);
    left->move(1220,825);
    right->move(1420,825);

    up->setText("↑");
    up->setShortcut(QKeySequence(Qt::Key_W));
    down->setText("↓");
    down->setShortcut(QKeySequence(Qt::Key_S));
    left->setText("←");
    left->setShortcut(QKeySequence(Qt::Key_A));
    right->setText("→");
    left->setShortcut(QKeySequence(Qt::Key_D));

    up->setStyleSheet("QPushButton{border:0px}");
    down->setStyleSheet("QPushButton{border:0px}");
    left->setStyleSheet("QPushButton{border:0px}");
    right->setStyleSheet("QPushButton{border:0px}");

    QFont ft("宋体",36);
    up->setFont(ft);
    down->setFont(ft);
    right->setFont(ft);
    left->setFont(ft);

    connect(up,&QPushButton::clicked,[=](){
        if(moveDirect!= SnakeDirect::DOWN)
        {
            moveDirect = SnakeDirect::UP;
        }
    });

    connect(down,&QPushButton::clicked,[=](){
        if(moveDirect!= SnakeDirect::UP)
        {
            moveDirect = SnakeDirect::DOWN;
        }
    });

    connect(left,&QPushButton::clicked,[=](){
        if(moveDirect!= SnakeDirect::RIGHT)
        {
            moveDirect = SnakeDirect::LEFT;
        }
    });

    connect(right,&QPushButton::clicked,[=](){
        if(moveDirect!= SnakeDirect::LEFT)
        {
            moveDirect = SnakeDirect::RIGHT;
        }
    });


    //退出游戏
    QPushButton*ExitBtn = new QPushButton(this);
    ExitBtn->setText("退出游戏");
    ExitBtn->move(1240,400);
    ExitBtn->setFont(font);
    QMessageBox *msg = new QMessageBox(this);
    QPushButton *ok = new QPushButton("ok");
    QPushButton *canel = new QPushButton("canel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(canel,QMessageBox::RejectRole);


    msg->setWindowTitle("退出游戏");
    msg->setText("确认退出游戏吗");

    connect(ExitBtn,&QPushButton::clicked,[=](){
        msg->show();
        msg->exec();//时间轮询
        QSound::play("res/clicked.wav");

        GameSelect *select = new GameSelect;


        if(msg->clickedButton()==ok)
        {
            this->close();
            select->show();
        }
        else {
            msg->close();
        }
    });
}

void gameroom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);//实例画家对象

    QPixmap pix;
    pix.load(":res/game_room.png");
    painter.drawPixmap(0,0,1200,1400,pix);

    pix.load(":res/bg1.png");
    painter.drawPixmap(1200,0,300,1100,pix);


    //绘制蛇

    //头
    if(moveDirect == SnakeDirect::UP)
    {
        pix.load(":res/up.png");
    }
    else if (moveDirect == SnakeDirect::DOWN) {
        pix.load(":res/down.png");
    }
    else if (moveDirect == SnakeDirect::LEFT) {
        pix.load(":res/left.png");
    }
    else if(moveDirect == SnakeDirect::RIGHT){
        pix.load(":res/right.png");
    }

    auto snakHead =  snakeList.front();
    painter.drawPixmap(snakHead.x(),snakHead.y(),snakHead.width(),snakHead.height(),pix);

    //身体
    pix.load(":res/Bd.png");
    for (int  i= 1;i < snakeList.size()-1;i++) {
        auto node = snakeList.at(i);   //at 获取每一个节点
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pix);
    }

    //尾巴
    auto snakeTail = snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pix);


    //食物
    pix.load(":res/food.png");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pix);



    //分数
    pix.load(":res/sorce_bg.png");
    painter.drawPixmap(this->width()*0.85,this->height()*0.1,90,40,pix);

    QPen pen;
    pen.setColor(Qt::black);
    QFont font("方正舒体",22);
    painter.setFont(font);
    painter.setPen(pen);
    painter.drawText(this->width()*0.9,this->height()*0.06,QString("%1").arg(snakeList.size()));


    //往文件中写分数
    int c = snakeList.size();
    QFile file("C:/Users/zyy/Desktop/1.txt");
    if(file.open(QIODevice::WriteOnly| QIODevice::Text))
    {
        QTextStream out(&file);
        int num = c;
        out<<num ;
        file.close();
    }

    //绘制有戏失败的效果
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("方正舒体",22);
        painter.setFont(font);
        painter.drawText(this->width()*0.45,this->height()*0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":res/gameover.wav");

        sound->stop();
    }
}

void gameroom::moveUp()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakeNode = snakeList.front();//头
    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(heady < 0)
    {
        //穿墙了
        leftTop = QPointF(headx,this->height()-KSnakeNodeHeight);
    }
    else {
        leftTop = QPointF(headx,heady- KSnakeNodeHeight);

    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);

     snakeList.push_front(QRectF(leftTop,rightBottom));//更新到链表中
}

void gameroom::moveDown()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakeNode = snakeList.front();
    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(heady > this->height())
    {
        leftTop = QPointF(headx,0);

    }
    else {
        leftTop =snakeNode.bottomLeft();//获取左下角做标
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));

}

void gameroom::moveLeft()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakeNode = snakeList.front();
    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(headx < 0)
    {
        leftTop = QPointF(1500 - KSnakeNodeWidth,heady);
    }
    else {
        leftTop = QPointF(headx - KSnakeNodeWidth,heady);
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void gameroom::moveRight()
{
    QPointF leftTop;//左上角坐标
    QPointF rightBottom;//右下角坐标

    auto snakeNode = snakeList.front();
    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(heady + KSnakeNodeWidth> 1200)
    {
        leftTop = QPointF(0,heady);

    }
    else {
        leftTop = snakeNode.bottomRight();
    }

    rightBottom = leftTop + QPointF(KSnakeNodeWidth,KSnakeNodeHeight);


    snakeList.push_front(QRectF(leftTop,rightBottom));
}

bool gameroom::checkFail()
{
    for(int  i = 0; i<snakeList.size();i++)
    {
        for(int j=i+1; j<snakeList.size();j++)
        {
            if(snakeList.at(i)==snakeList.at(j))
            {
                return  true;
            }
        }
    }
    return  false;
}

void gameroom::createNewFood()
{
    foodRect = QRectF(qrand()%(1500/KSnakeNodeWidth)*KSnakeNodeWidth,
                      qrand()%(this->height()/KSnakeNodeHeight)*KSnakeNodeHeight,
                      KSnakeNodeWidth,KSnakeNodeHeight);
}





















